package com.sxm.yiwei.fragments;


import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.UserRegistActivity;
import com.sxm.yiwei.activitis.UserUpActivity;
import com.sxm.yiwei.tools.REXTools;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.ValidationCode;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegistFragment extends Fragment implements View.OnClickListener{

    private String TAG = "regist";
    private ValidationCode zixing;
    private EditText inphone;
    private EditText inword;
    private EditText inwordto;
    private EditText inpiccode;
    private EditText inphonecode;
    private ImageView phoneclear;
    private ImageView wordclear;
    private ImageView wordtoeclear;
    private Button phonecodebt;
    private Button userRegist;
    private SharedPreferences sharedPreferences;
    private String rid;
    private String appid;
    private String longitude;
    private String latitude;
    private String data;
    private String messageId;
    private SharedPreferences shared;
    private SharedPreferences.Editor edit;
    private String inpiccodes;
    private String phone;
    private String word;
    private String wordto;
    private String aesword;
    private String phonecode;
    private String userId;
    private String token;

    public RegistFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_regist, container, false);
        sharedPreferences = getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        rid = sharedPreferences.getString("rid", "");
        appid = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        initRegistFView(view);
        return view;
    }
    private void initRegistFView(View view) {
        zixing = (ValidationCode) view.findViewById(R.id.regidt_zixing);
        inphone = (EditText) view.findViewById(R.id.regist_inphone);
        inword = (EditText) view.findViewById(R.id.regist_inword);
        inwordto = (EditText) view.findViewById(R.id.regist_inwordtoo);
        inpiccode = (EditText) view.findViewById(R.id.regist_piccode);
        inphonecode = (EditText) view.findViewById(R.id.regist_phonecode);
        phoneclear = (ImageView) view.findViewById(R.id.regist_phoneclear);
        wordclear = (ImageView) view.findViewById(R.id.regist_wordclear);
        wordtoeclear = (ImageView) view.findViewById(R.id.regist_wordtoclear);
        phonecodebt = (Button) view.findViewById(R.id.regist_phonecodebt);
        userRegist = (Button) view.findViewById(R.id.regist_userregist);
        // 按钮监听
        zixing.setOnClickListener(this);
        phoneclear.setOnClickListener(this);
        wordclear.setOnClickListener(this);
        wordtoeclear.setOnClickListener(this);
        phonecodebt.setOnClickListener(this);
        userRegist.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.regidt_zixing:

                break;
            case R.id.regist_phonecodebt:
                getInPutData();
                if (phone.equals("")){
                    Toast.makeText(getActivity(), "请填写手机号码", Toast.LENGTH_SHORT).show();
                }else {
                   if (REXTools.isPhoneNumber(phone)){
                       if (word.equals("")){
                           Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
                       }else {
                           if (wordto.equals("")){
                               Toast.makeText(getActivity(), "请确认密码", Toast.LENGTH_SHORT).show();
                           }else {
                               if (!word.equals(wordto)){
                                   Toast.makeText(getActivity(), "请确定密码输入一致", Toast.LENGTH_SHORT).show();
                               }else {
                                   if (inpiccodes.equals("")){
                                       Toast.makeText(getActivity(), "请填写图形验证码", Toast.LENGTH_SHORT).show();
                                   }else {
                                       if (inpiccodes.equals(zixing.getCodeString())){
                                          MyTimer timer = new MyTimer(120000,1000);
                                           timer.start();
                                           getCode();

                                           Toast.makeText(getActivity(), "验证码已发送", Toast.LENGTH_SHORT).show();
                                       }else {
                                           Toast.makeText(getActivity(), "请填写正确的图形验证码,注意大小写哦", Toast.LENGTH_SHORT).show();
                                       }
                                   }
                               }
                           }
                       }

                   }else {
                       Toast.makeText(getActivity(), "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                   }

                }

                break;
            case R.id.regist_phoneclear:
                inphone.setText("");
                break;
            case R.id.regist_wordclear:
                inword.setText("");
                break;
            case R.id.regist_wordtoclear:
                inwordto.setText("");
                break;
            case R.id.regist_userregist:
                getInPutData();
                UserRegist();
                break;
        }
    }
    //获取输入内容
    private void getInPutData() {
        inpiccodes = String.valueOf(inpiccode.getText());// 图形验证码
        phone = String.valueOf(inphone.getText()); //手机号
        word = String.valueOf(inword.getText()); // 密码
        wordto = String.valueOf(inwordto.getText()); //确认密码
        phonecode = String.valueOf(inphonecode.getText());
    }
    // 获取短信验证码
    public void getCode() {
        RequestParams param1 = new RequestParams(InternetAddressUtis.Url+"/verify/sendCodeNotLogin");// 验证码接口
        param1.addHeader("Content-Type","application/json");
        param1.addHeader("appId",appid);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("mobile",phone);
        object.put("type","1");
        param1.addParameter("params",object.toJSONString());
        x.http().get(param1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: 验证码--"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取appid
                data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                messageId = obj1.getString("messageId");
                shared = getActivity().getSharedPreferences("messageId", Context.MODE_PRIVATE);
                edit = shared.edit();
                edit.putString("messageId", messageId);
                edit.commit();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: 验证码是--"+ex);
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {

            }
        });
    }

    // 用户注册
    private void UserRegist() {
        try {
            aesword = AESUtil.encryptAES(word);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/userRegister");//注册接口
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId",appid);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("mobile",phone);
        object.put("password", aesword);
        object.put("latitude",latitude);
        object.put("longitude",longitude);
        object.put("messageId", messageId);
        object.put("code",phonecode);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                // 注册成功以后 可以此处添加账号密码
                Log.d(TAG, "onSuccess: zhuce---"+result);
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(getActivity(), "注册成功,你可以登陆一喂了", Toast.LENGTH_SHORT).show();
                    String data = obj.getString("data");
                    com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                    userId = obj1.getString("userId");
                    token = obj1.getString("token");
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("userId", userId);
                    edit.putString("token", token);
                    edit.commit();
                }else {
                    String failure = obj.getString("failure");
                    if (failure.equals("1001")){
                        Toast.makeText(getActivity(), "该手机号已被注册", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1003")){
                        Toast.makeText(getActivity(), "账号被禁用", Toast.LENGTH_SHORT).show();

                    }else if (failure.equals("1005")){
                        Toast.makeText(getActivity(), "短信验证码错误", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: no-注册-"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
        //120s 倒计时
    class MyTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                  倒计时数        to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *           倒计时间隔               {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            phonecodebt.setClickable(false);
            phonecodebt.setText(millisUntilFinished/1000+"s");
        }

        @Override
        public void onFinish() {
            phonecodebt.setClickable(true);
            phonecodebt.setText("验证码");
        }
    }
}
